package com.aps.server.service;

import com.aps.common.boot.CoreApplicationContext;
import com.aps.common.service.TestGenericService;
import com.aps.server.entity.ApsOperation;
import com.aps.server.entity.BasicOperation;
import com.aps.server.mapper.BasicOperationMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 工序信息服务类
 * 提供工序信息相关的业务逻辑处理
 */
@Slf4j
@Service
public class BasicOperationService extends TestGenericService {
    @Resource
    BasicOperationMapper basicOperationMapper;

    
    /**
     * 创建工序信息
     * 
     * @param basicOperation 工序信息
     * @return 是否创建成功
     */
    public boolean createOperation(BasicOperation basicOperation) {
        // 自动设置租户ID
        if (basicOperation.getTenantId() == null || basicOperation.getTenantId().trim().isEmpty()) {
            basicOperation.setTenantId(getCurrentTenantId());
        }
        
        basicOperation.setCreateTime(LocalDateTime.now());
        basicOperation.setUpdateTime(LocalDateTime.now());
        
        int result = basicOperationMapper.insert(basicOperation);
        log.info("创建工序信息结果: {}, 工序ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", basicOperation.getId(), basicOperation.getTenantId());
        return result > 0;
    }
    
    /**
     * 根据ID查询工序信息
     * 
     * @param id 工序ID
     * @return 工序信息
     */
    public BasicOperation getOperationById(Integer id) {
        String tenantId = getCurrentTenantId();
        QueryWrapper<BasicOperation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("tenant_id", tenantId);
        
        BasicOperation operation = basicOperationMapper.selectOne(queryWrapper);
        log.info("查询工序信息ID: {}, 租户ID: {}, 结果: {}", id, tenantId, operation != null ? "找到" : "未找到");
        return operation;
    }
    
    /**
     * 根据ID和指定租户ID查询工序信息
     * 
     * @param id 工序ID
     * @param tenantId 租户ID
     * @return 工序信息
     */
    public BasicOperation getOperationById(Integer id, String tenantId) {
        QueryWrapper<BasicOperation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("tenant_id", tenantId);
        
        BasicOperation operation = basicOperationMapper.selectOne(queryWrapper);
        log.info("查询工序信息ID: {}, 租户ID: {}, 结果: {}", id, tenantId, operation != null ? "找到" : "未找到");
        return operation;
    }
    
    /**
     * 更新工序信息
     * 
     * @param basicOperation 工序信息
     * @return 是否更新成功
     */
    public boolean updateOperation(BasicOperation basicOperation) {
        basicOperation.setUpdateTime(LocalDateTime.now());
        
        QueryWrapper<BasicOperation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", basicOperation.getId()).eq("tenant_id", basicOperation.getTenantId());
        
        int result = basicOperationMapper.update(basicOperation, queryWrapper);
        log.info("更新工序信息结果: {}, 工序ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", basicOperation.getId(), basicOperation.getTenantId());
        return result > 0;
    }
    
    /**
     * 删除工序信息
     * 
     * @param id 工序ID
     * @return 是否删除成功
     */
    public boolean deleteOperation(Integer id) {
        String tenantId = getCurrentTenantId();
        return deleteOperation(id, tenantId);
    }
    
    /**
     * 根据ID和租户ID删除工序信息
     * 
     * @param id 工序ID
     * @param tenantId 租户ID
     * @return 是否删除成功
     */
    public boolean deleteOperation(Integer id, String tenantId) {
        QueryWrapper<BasicOperation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("tenant_id", tenantId);
        
        int result = basicOperationMapper.delete(queryWrapper);
        log.info("删除工序信息结果: {}, 工序ID: {}, 租户ID: {}", result > 0 ? "成功" : "失败", id, tenantId);
        return result > 0;
    }
    
    /**
     * 查询当前租户的工序列表
     * 
     * @return 工序列表
     */
    public List<BasicOperation> getOperationsByTenantId() {
        String tenantId = getCurrentTenantId();
        return getOperationsByTenantId(tenantId);
    }
    
    /**
     * 根据租户ID查询工序列表
     * 
     * @param tenantId 租户ID
     * @return 工序列表
     */
    public List<BasicOperation> getOperationsByTenantId(String tenantId) {
        List<BasicOperation> operations = basicOperationMapper.selectByTenantId(tenantId);
        log.info("根据租户ID查询工序列表, 租户ID: {}, 数量: {}", tenantId, operations.size());
        return operations;
    }
    
    /**
     * 分页查询当前租户的工序列表
     * 
     * @param current 当前页
     * @param size 每页大小
     * @return 分页工序列表
     */
    public IPage<BasicOperation> getOperationsByTenantIdPage(int current, int size) {
        String tenantId = getCurrentTenantId();
        return getOperationsByTenantIdPage(current, size, tenantId);
    }
    
    /**
     * 根据租户ID分页查询工序列表
     * 
     * @param current 当前页
     * @param size 每页大小
     * @param tenantId 租户ID
     * @return 分页工序列表
     */
    public IPage<BasicOperation> getOperationsByTenantIdPage(int current, int size, String tenantId) {
        Page<BasicOperation> page = new Page<>(current, size);
        IPage<BasicOperation> result = basicOperationMapper.selectPageByTenantId(page, tenantId);
        log.info("分页查询工序列表, 租户ID: {}, 当前页: {}, 每页大小: {}, 总数: {}", tenantId, current, size, result.getTotal());
        return result;
    }
    
    /**
     * 根据工艺编码查询工序列表
     * 
     * @param craftId 工艺编码
     * @param tenantId 租户ID
     * @return 工序列表
     */
    public List<BasicOperation> getOperationsByCraftId(String craftId, String tenantId) {
        List<BasicOperation> operations = basicOperationMapper.selectByCraftId(craftId, tenantId);
        log.info("根据工艺编码查询工序列表, 工艺编码: {}, 租户ID: {}, 数量: {}", craftId, tenantId, operations.size());
        return operations;
    }
    
    /**
     * 根据工艺编码分页查询工序列表
     * 
     * @param current 当前页
     * @param size 每页大小
     * @param craftId 工艺编码
     * @param tenantId 租户ID
     * @return 分页工序列表
     */
    public IPage<BasicOperation> getOperationsByCraftIdPage(int current, int size, String craftId, String tenantId) {
        Page<BasicOperation> page = new Page<>(current, size);
        IPage<BasicOperation> result = basicOperationMapper.selectPageByCraftId(page, craftId, tenantId);
        log.info("分页查询工序列表, 工艺编码: {}, 租户ID: {}, 当前页: {}, 每页大小: {}, 总数: {}", craftId, tenantId, current, size, result.getTotal());
        return result;
    }
    
    /**
     * 根据工序名称查询工序信息
     * 
     * @param operationName 工序名称
     * @param tenantId 租户ID
     * @return 工序信息
     */
    public BasicOperation getOperationByOperationName(String operationName, String tenantId) {
        BasicOperation operation = basicOperationMapper.selectByOperationName(operationName, tenantId);
        log.info("根据工序名称查询工序信息, 工序名称: {}, 租户ID: {}, 结果: {}", operationName, tenantId, operation != null ? "找到" : "未找到");
        return operation;
    }
    
    /**
     * 根据工序类型查询工序列表
     * 
     * @param operationType 工序类型
     * @param tenantId 租户ID
     * @return 工序列表
     */
    public List<BasicOperation> getOperationsByOperationType(String operationType, String tenantId) {
        List<BasicOperation> operations = basicOperationMapper.selectByOperationType(operationType, tenantId);
        log.info("根据工序类型查询工序列表, 工序类型: {}, 租户ID: {}, 数量: {}", operationType, tenantId, operations.size());
        return operations;
    }
    
    /**
     * 根据设备类型要求查询工序列表
     * 
     * @param equipmentTypeRequire 设备类型要求
     * @param tenantId 租户ID
     * @return 工序列表
     */
    public List<BasicOperation> getOperationsByEquipmentTypeRequire(String equipmentTypeRequire, String tenantId) {
        List<BasicOperation> operations = basicOperationMapper.selectByEquipmentTypeRequire(equipmentTypeRequire, tenantId);
        log.info("根据设备类型要求查询工序列表, 设备类型要求: {}, 租户ID: {}, 数量: {}", equipmentTypeRequire, tenantId, operations.size());
        return operations;
    }
    
    /**
     * 统计租户下的工序数量
     * 
     * @param tenantId 租户ID
     * @return 工序数量
     */
    public Long countOperationsByTenantId(String tenantId) {
        Long count = basicOperationMapper.countByTenantId(tenantId);
        log.info("统计租户工序数量, 租户ID: {}, 数量: {}", tenantId, count);
        return count;
    }
    
    /**
     * 统计工艺编码下的工序数量
     * 
     * @param craftId 工艺编码
     * @param tenantId 租户ID
     * @return 工序数量
     */
    public Long countOperationsByCraftId(String craftId, String tenantId) {
        Long count = basicOperationMapper.countByCraftId(craftId, tenantId);
        log.info("统计工艺工序数量, 工艺编码: {}, 租户ID: {}, 数量: {}", craftId, tenantId, count);
        return count;
    }
    
    /**
     * 统计租户下指定类型的工序数量
     * 
     * @param operationType 工序类型
     * @param tenantId 租户ID
     * @return 工序数量
     */
    public Long countOperationsByOperationType(String operationType, String tenantId) {
        Long count = basicOperationMapper.countByOperationType(operationType, tenantId);
        log.info("统计租户指定类型工序数量, 工序类型: {}, 租户ID: {}, 数量: {}", operationType, tenantId, count);
        return count;
    }
    
    /**
     * 批量创建工序信息
     * 
     * @param operations 工序信息列表
     * @return 成功创建的数量
     */
    public int batchCreateOperations(List<BasicOperation> operations) {
        if (operations == null || operations.isEmpty()) {
            return 0;
        }
        
        String tenantId = getCurrentTenantId();
        LocalDateTime now = LocalDateTime.now();
        
        int successCount = 0;
        for (BasicOperation operation : operations) {
            try {
                if (operation.getTenantId() == null || operation.getTenantId().trim().isEmpty()) {
                    operation.setTenantId(tenantId);
                }
                operation.setCreateTime(now);
                operation.setUpdateTime(now);
                
                int result = basicOperationMapper.insert(operation);
                if (result > 0) {
                    successCount++;
                }
            } catch (Exception e) {
                log.error("批量创建工序信息失败, 工序名称: {}", operation.getOperationName(), e);
            }
        }
        
        log.info("批量创建工序信息完成, 总数: {}, 成功: {}", operations.size(), successCount);
        return successCount;
    }

}
